package com.google.code.irouter.portal.client.dashboard.main.north.menu.switcher;

import java.util.List;

import com.google.code.irouter.portal.client.AppConstants;
import com.google.code.irouter.portal.client.rpc.solution.SolutionResult;
import com.google.code.irouter.portal.client.rpc.solution.SolutionService;
import com.google.code.irouter.portal.client.rpc.solution.SolutionServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.widgets.menu.Item;
import com.gwtext.client.widgets.menu.Menu;

public final class Solutions extends Menu {
	
	private static final AppConstants CONSTANTS = GWT.create(AppConstants.class);
	
	private final SolutionServiceAsync solutionService = GWT.create(SolutionService.class);
	
	public static String COOKIE_SOLUTION = Solutions.class.getName();

	public Solutions() {
		super();
		this.setId(Solutions.class.getName());
		
		this.addListener(new SolutionsListener());
	}

	public void addItem(String name, String value) {
		Item ui = new Item();
		ui.setText(name);
		ui.setStateId(value);
		this.addItem(ui);
	}

	public void refresh() {
		this.removeAll();
		this.addItem(CONSTANTS.com_google_code_irouter_portal_client_common_processing(),"");
		solutionService.load(
				new AsyncCallback<List<SolutionResult>>() {
					public void onFailure(Throwable caught) {
					// TODO
						hide();
					}

					public void onSuccess(List<SolutionResult> solutionResultList) {
						removeAll();
						for(SolutionResult solutionResult : solutionResultList) {
							addItem(solutionResult.getName(), solutionResult.getId());
						}
						if(getItems().length == 0)
							hide();
					}
				}
		);
	}
	
	public void select(final String menuId) {
		solutionService.select(
				this.getItem(menuId).getStateId(),
				new AsyncCallback<Boolean>() {
					public void onFailure(Throwable caught) {
					}

					public void onSuccess(Boolean result) {
						if(result) {
							Cookies.setCookie(COOKIE_SOLUTION, getItem(menuId).getStateId());
							Window.open("Dashboard.html", "_self", "");
						}						
					}
				}
		);		
		
	}

}